import json
from django.utils import timezone
from django.http import HttpResponse

from login_auth.models import *


# Create your views here.

def auth(request):
    if request.method != 'POST':
        return JsonResponseUtf8({}, 405, False, "方法不允许")
    session = request.session.get("info")
    if session is not None:
        return JsonResponseUtf8(session, 200, True, "操作成功")
    username = request.POST.get("username")
    password = request.POST.get("password")
    if username is None or password is None:
        return JsonResponseUtf8({}, 404, False, "会话过期")
    user = User.objects.filter(username=username, password=password).first()
    if user is None:
        return JsonResponseUtf8({}, 404, False, "用户名或密码错误")
    data = {
        "username": username,
        "role": user.role,
        "name": user.name,
        "phone": user.phone,
        "timeDescribe": getHourTime()
    }
    request.session['info'] = data
    return JsonResponseUtf8(data, 200, True, "操作成功")


def logout(request):
    session = request.session.get("info")
    if session is not None:
        del request.session["info"]
    return JsonResponseUtf8({}, 200, True, "登出成功")


def getHourTime():
    time = timezone.now()
    time = str(time)
    nowtime = time[11:13]
    if nowtime[0] == 0:
        nowtime = nowtime[1]
    if int(nowtime) in range(5, 8):
        return "早上好！"
    if int(nowtime) in range(8, 12):
        return "上午好！"
    if int(nowtime) in range(12, 13):
        return "中午好！"
    if int(nowtime) in range(13, 17):
        return "下午好！"
    if int(nowtime) in range(17, 24) or int(nowtime) in range(0, 5):
        return "晚上好！"


def JsonResponseUtf8(data, code: int, success: bool, message: str):
    rtn = {
        "data": data,
        "code": code,
        "success": success,
        "message": message
    }
    return HttpResponse(
        json.dumps(rtn, ensure_ascii=False),
        content_type="application/json,charset=utf-8"
    )
